package net.begincode.SSO.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.begincode.SSO.util.ConfigFileUtil;
import net.begincode.SSO.util.http.HTTPClientUtil;

/**
 * 插入业务系统的过滤器，拦截登录请求
 * 访问认证系统认证
 * @author 遗忘
 * @date 2017.5.8
 *
 */
public class LoginFilter implements Filter {
	public static final String VERIFY_URL = "http://localhost:8080/SSO-web/user/verify.htm"; //验证接口的地址
	public static final String LOGIN_FILTER_URL = "http://localhost:8080/SSO-web/loginstate"; //用来获取登录状态返回ticket的地址
	private  String loginFilterUrl;
	private String verifyUrl;
	
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
		/* 获取cookie存取的短期凭证 ，存在则证明已进行校验，放行 */
			for(Cookie cookie:cookies){
				if("loginState".equals(cookie.getName())){
					chain.doFilter(request, response);
					return;
				}
			}
		}
		
		Properties properties = ConfigFileUtil.getProperties(this.getClass(), "URLConfig.properties");
		if(properties.isEmpty()||properties.getProperty("LOGIN_FILTER_URL")==null||properties.getProperty("VERIFY_URL")==null){
			loginFilterUrl = LOGIN_FILTER_URL;
			verifyUrl= VERIFY_URL;
		}else{
			loginFilterUrl = properties.getProperty("LOGIN_FILTER_URL");
			verifyUrl=properties.getProperty("VERIFY_URL");
		}
		String backURL = request.getQueryString()!=null?(request.getRequestURL().toString()+"?"+request.getQueryString()):request.getRequestURL().toString();
		String ticket = request.getParameter("ticket");
		backURL = backURL.indexOf("ticket=")!=-1?backURL.substring(0, backURL.indexOf("ticket=")):backURL;
		if(ticket==null||"".equals(ticket)){
			response.sendRedirect(loginFilterUrl+"?backURL="+backURL);
			return;
		}else{
			String logoutURL = "http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/logout";
			 Map<String, String> param = new HashMap<String,String>();
			param.put("backURL", backURL);
			param.put("logoutURL", logoutURL);
			param.put("ticket", ticket);
			
			//HTTP访问
			String result = HTTPClientUtil.postRequest(verifyUrl, param);
			
			if("false".equals(result)){
				response.sendRedirect(loginFilterUrl+"?backURL="+backURL);
				return;
			}else if("true".equals(result)){
				Cookie cookie = new Cookie("loginState", result);
				cookie.setMaxAge(60*30);
				cookie.setPath("/");
				response.addCookie(cookie);
				response.sendRedirect(backURL);
				return;
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
